<template>
  <div class="drag" ref="dragDiv">
    <div class="drag-text">{{ msg }}</div>
    <div
      class="block block-bg"
      :class="{ block_ok_bg: is_success }"
      @touchstart="touchstart($event)"
      @touchmove="touchmove($event)"
      @touchend="touchend($event)"
      ref="moveDiv"
    ></div>
  </div>
</template>

<script>
import { onMounted, ref } from "vue";
export default {
  name: "Drag",
  setup(props,context) {
    let msg = ref("请先滑动解锁");
    //定义滑块是否解锁成功的状态
    let is_success = ref(false);
    let XStart = 0;
    let maxWidth = "";

    //滑动解锁的 大盒子
    let dragDiv = ref(null);
    //拖动的小盒子
    let moveDiv = ref(null);

    //给拖动moveDiv绑定 触摸开始、触摸移动、触摸结束三个事件，改变moveDiv的位置
    function touchstart(event) {
      //这里为什么要阻止默认行为？
      event.preventDefault && event.preventDefault();
      if (!is_success.value) {
        //首先我们必须要知道：鼠标在拖动小盒子在x轴上拖动初始位置
        XStart = event.touches[0].clientX;
        // console.log("我是拖动小盒子的 x轴初始距离", XStart);
      }
    }

    function touchmove(event) {
      event.preventDefault && event.preventDefault();
      if (!is_success.value) {
        //拖动小盒子移动的距离为 开始触摸移动的 X轴方向的距离
        let XMove = event.changedTouches[0].clientX;
        // console.log(event);
        // console.log("我是一直在变化的 触摸移动鼠标X轴距离", XMove);
        if (XMove - XStart < maxWidth) {
          moveDiv.value.style.left = XMove - XStart + "px";
        } else {
          moveDiv.value.style.left = maxWidth + "px";
        }
      }
    }

    function touchend(event) {
      event.preventDefault && event.preventDefault();
      if (!is_success.value) {
        //触摸结束位置未到终点 则小盒子复原到起始位置
        if (event.changedTouches[0].clientX - XStart < maxWidth) {
          moveDiv.value.style = "0px";
        } else {
          msg.value = "解锁成功";
          is_success.value = true;
          dragDiv.value.style.backgroundColor = "green";

          //关键？？？
          context.emit("unlock");
        }
      }
    }

    //关键：在页面一挂载的时候就 获取滑动成功要走的X轴距离：maxWidth
    onMounted(() => {
      maxWidth = dragDiv.value.clientWidth - moveDiv.value.clientWidth;
      console.log(maxWidth);
    });

    return {
      msg,
      is_success,
      moveDiv,
      dragDiv,
      touchstart,
      touchmove,
      touchend,
    };
  },
};
</script>

<style lang="less" scoped>
.drag {
  position: relative;
  background-color: lightgray;
  width: 100%;
  height: 45px;
  line-height: 45px;
  text-align: center;
  border-radius: 5px;
  
  .block {
    width: 60px;
    height: 45px;
    border-radius: 5px;
    cursor: move;
    position: absolute;
    top: 0;
    left: 0;
  }
  .block-bg {
    background: gray url("../assets/image/arrow.png") no-repeat center;
    background-size: 20px 20px;
  }
  .block_ok_bg {
    background: gray url("../assets/image/success.png") no-repeat center;
    background-size: 20px 20px;
  }
}
</style>